package main

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"strconv"
	"testapp/Logic/member"
	"time"
)

func main() {
	//创建一个多路复用器
	mux := http.NewServeMux()

	//注册一个路由
	//用户注册
	mux.HandleFunc("/register", func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, "注册111测试")
	})

	//登录
	mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {

		//页面渲染
		if r.Method == "GET" {
			//解析模板
			t, _ := template.ParseFiles("./Tpl/login.gtpl")

			//表单令牌
			//创建MD5对象
			md5_obj := md5.New()
			//当前Unix时间戳
			current_time := time.Now().Unix()
			//当前时间戳写入md5对象中
			io.WriteString(md5_obj, strconv.FormatInt(current_time, 10))
			//格式化成十六进制
			form_token := fmt.Sprintf("%x", md5_obj.Sum(nil))

			//执行模板
			t.Execute(w, form_token)
			return
		}

		//逻辑处理
		status, msg := member.Login()
		if status == 1 {
			io.WriteString(w, msg+"5858")
		}

	})

	//测试实践
	mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {

	})

	//json
	mux.HandleFunc("/json", func(w http.ResponseWriter, r *http.Request) {
		//主机属性结构
		type Server struct {
			Id   int    `json:",string"`
			Name string `json:"name"`
			Ip   string `json:"ip"`
		}

		type Serverlist struct {
			Servers []Server `json:"servers"`
		}

		//一维JSON
		var s_o Server
		s_o.Id = 1
		s_o.Name = "jirenyou"
		s_o.Ip = "192.168.1.1"
		//转成json
		s_o_j, _ := json.Marshal(s_o)

		fmt.Println(string(s_o_j))
		io.WriteString(w, string(s_o_j))

		//多维JSON
		var s Serverlist
		s.Servers = append(s.Servers, Server{Id: 1, Name: "web服务节点-1", Ip: "192.168.1.10"})
		//转成json
		json_data, err := json.Marshal(s)
		if err != nil {
			fmt.Println("json encode error:", err)
		}

		fmt.Println(string(json_data))
		io.WriteString(w, string(json_data))

	})

	//template模板
	mux.HandleFunc("/template", func(w http.ResponseWriter, r *http.Request) {
		type Firend struct {
			Fname string
		}

		type Person struct {
			Name    string
			Email   []string
			Friends []*Firend
		}

		f1 := Firend{Fname: "jirenyou"}
		f2 := Firend{Fname: "jirenyou_test"}

		//加载模板
		t, err := template.ParseFiles("./Tpl/template.gtpl")
		if err != nil {
			fmt.Println(err)
		}

		//解析模板
		//		t, _ = t.Parse(`hello,{{.Name}}!
		//		{{range .Email}}
		//		an email {{.}}
		//		{{end}}
		//		{{with .Friends}}
		//			{{range .}}
		//				my firend name is {{.Fname}}
		//			{{end}}
		//		{{end}}
		//		`)

		//输出数据
		p := Person{Name: "aa", Email: []string{"390066398@qq.com", "jiry@pad-phone.com"}, Friends: []*Firend{&f1, &f2}}

		//执行模板
		t.Execute(w, p)

	})

	//监听端口
	err := http.ListenAndServe(":9090", mux)

	if err != nil {
		fmt.Println(err)
	}
}
